package tmp.antlr;

import java.util.List;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.antlr.v4.runtime.tree.TerminalNode;

import a2.EEvalueBaseListener;
import a2.EEvalueLexer;
import a2.EEvalueParser;
import a2.EEvalueParser.AtomContext;
import a2.EEvalueParser.ExpressionContext;
import a2.EEvalueParser.MultExprContext;

public class Test2 {

	public static void main(String[] args) throws Exception{
		run("1+4*2/(1-5)");

	}

	public static void run(String expr)throws Exception{
		ANTLRInputStream in = new ANTLRInputStream(expr);
		EEvalueLexer lexer = new EEvalueLexer(in);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		EEvalueParser parser = new EEvalueParser(tokens);
		
		ExpressionContext expressionContext = parser.expression();
		System.out.println("result = " + expressionContext.value);
		
		ParseTreeWalker walker = new ParseTreeWalker();
		walker.walk(new EEvalueBaseListener(){
			@Override 
			public void exitExpression(@NotNull EEvalueParser.ExpressionContext ctx) { 
				List<MultExprContext> list = ctx.multExpr();
				for(MultExprContext multExprContext : list){
					System.out.println(multExprContext.getText());
				}
				System.out.println("============");
			}
			@Override 
			public void exitMultExpr(@NotNull EEvalueParser.MultExprContext ctx) {
				List<AtomContext> list = ctx.atom();
				for(AtomContext aContext : list){
					System.out.println("[exitMultExpr]" + aContext.getText());
				}
			}
			@Override
			public void exitAtom(@NotNull EEvalueParser.AtomContext ctx) {
				TerminalNode terminalNode = ctx.INT();
				if(terminalNode != null){
					System.out.println("[exitAtom]" + terminalNode.getText());
				}else{
					System.out.println("[exitAtom]" + ctx.expression().getText());
				}
			}
		}, expressionContext);
	}
}
